package com.hanbang.gycatering.comeon;

import org.json.JSONException;
import org.json.JSONObject;
import com.hanbang.gangyu.R;
import com.hanbang.gycatering.application.MyApplication;
import com.hanbang.gycatering.bean.UserInforData;
import com.hanbang.gycatering.homepage.BaseActivity;
import com.hanbang.gycatering.utils.DbUtil;
import com.hanbang.gycatering.utils.HttpInterfaces;
import com.hanbang.gycatering.utils.MyLog;
import com.hanbang.gycatering.utils.MyRequestCallBack;
import com.hanbang.gycatering.utils.MySharedPreferences;
import com.hanbang.gycatering.utils.MyToast;
import com.lidroid.xutils.DbUtils;
import com.lidroid.xutils.exception.DbException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

/*
 */
public class LoginActivity extends BaseActivity {
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login);
		initView();

	}

	private void initView() {
		// TODO Auto-generated method stub
		((TextView) findViewById(R.id.top_bar_title)).setText("用户登录");
		super.setBackArrows((ImageView) findViewById(R.id.top_bar_left_image));
		// iv.setOnClickListener(onClickListener);
		findViewById(R.id.user_login_row).setOnClickListener(onClickListener);
		TextView re = (TextView) findViewById(R.id.user_login_register_right);
		re.setOnClickListener(onClickListener);
		findViewById(R.id.user_login_forget_password).setOnClickListener(
				onClickListener);
	}

	private OnClickListener onClickListener = new OnClickListener() {
		@Override
		public void onClick(View view) {
			switch (view.getId()) {
			case R.id.user_login_row:
				String name = ((EditText) findViewById(R.id.login_name))
						.getText().toString().trim();
				String password = ((EditText) findViewById(R.id.login_password))
						.getText().toString().trim();
				if (!name.equals("") && !password.equals("")) {
					postService(name, password);
					// Intent intent = new Intent(WXEntryActivity.this,
					// MainActivity.class);
					// startActivity(intent);
					// finish();
				} else {
					MyToast.show(LoginActivity.this, "您未输入用户名或密码",
							Toast.LENGTH_SHORT);
				}
				break;
			case R.id.user_login_register_right:
				Intent intent2 = new Intent(LoginActivity.this,
						RegisterActivity.class);
				startActivityForResult(intent2, 999);
				break;
			case R.id.user_login_forget_password:
				Intent intent3 = new Intent(LoginActivity.this,
						ForgetPasswordActivity.class);
				startActivityForResult(intent3, 1000);
				break;
			default:
				break;
			}
		}
	};

	// 手机号登入
	private void postService(final String name, final String password) {
		MyLog.e("postService",  HttpInterfaces.loginuser + "&userphone=" + name
						+ "&password=" + password);
		((MyApplication) getApplicationContext()).httpUtils.send(
				HttpMethod.GET, HttpInterfaces.loginuser + "&userphone=" + name
						+ "&password=" + password,
				new MyRequestCallBack<String>(LoginActivity.this,
						getString(R.string.loadding)) {

					@Override
					public void onSuccess(ResponseInfo<String> responseInfo) {
						super.onSuccess(responseInfo);
						UserInforData data = null;
						try {
							JSONObject json = new JSONObject(
									responseInfo.result);
							int state = json.getInt("state");
							if (state == 1) {
								data = new UserInforData();
								JSONObject userinfo = json.getJSONArray("info")
										.getJSONObject(0);
								data.setUserId(userinfo.getInt("id"));
								data.setBalanc(userinfo.getString("balance"));
								data.setUsernick(userinfo.getString("name"));
								data.setUserphone(userinfo.getString("phone"));
								data.setUserpassword(userinfo
										.getString("password"));
								data.setPiont(userinfo.getString("point"));
								data.setAvatar(userinfo.getString("head"));
								data.setAddress(userinfo.getString("address"));
								data.setGrade(userinfo.getString("grade"));
								data.setPlotid(userinfo.getInt("plotid"));
								data.setPlotname(userinfo.getString("plotname")); 
								data.setRealname(userinfo.getString("realname"));
								data.setProvince(userinfo.getString("address"));
								if (data != null) {
									DbUtils dbUtils = DbUtil
											.getDbUtils(LoginActivity.this);
									// 把id 保存在sp
									MySharedPreferences
											.setSharedPreferencesKeyAndValue(
													LoginActivity.this,
													MySharedPreferences.USER_DATA,
													"user_id", data.getUserId());
									try {
										UserInforData u = dbUtils.findById(
												UserInforData.class,
												data.getUserId());
										if (u == null) {
											dbUtils.save(data);
										} else {
											dbUtils.saveOrUpdate(data);
										}
										MyLog.e("dbUtils", "保存成功");
									} catch (DbException e) {
										e.printStackTrace();
										MyToast.show(LoginActivity.this,
												"登录失败", Toast.LENGTH_SHORT);
										MySharedPreferences
												.setSharedPreferencesKeyAndValue(
														LoginActivity.this,
														MySharedPreferences.USER_DATA,
														"user_id", -1);
									}
									finish();
								}
//								MyToast.show(LoginActivity.this,
//										json.getString("erro"),
//										Toast.LENGTH_SHORT);
							} else {
								MyToast.show(LoginActivity.this,
										"登录失败,检查账号或者密码是否正确!",
										Toast.LENGTH_SHORT);
								MySharedPreferences
										.setSharedPreferencesKeyAndValue(
												LoginActivity.this,
												MySharedPreferences.USER_DATA,
												"user_id", -1);
							}

						} catch (JSONException e) {
							e.printStackTrace();
						}
					}
				});
	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == 999 && resultCode == 999) {
			MyLog.e("onActivityResult", "返回成功");
			postService(data.getStringExtra("userphone"),
					data.getStringExtra("password"));

		}
		if (requestCode == 1000 && resultCode == 1000) {

		}

	};

}
